package com.huashi.dealer.core.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.time.*;

@MappedJdbcTypes({JdbcType.BIGINT, JdbcType.INTEGER})
@MappedTypes(LocalDateTime.class)
public class EpochLocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {

    private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
            throws SQLException {
        long epochSeconds = parameter.atZone(ZONE).toInstant().getEpochSecond(); // 秒
        ps.setLong(i, epochSeconds);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long v = rs.getLong(columnName);
        if (rs.wasNull() || v <= 0L) return null;
        return toLocalDateTime(v);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long v = rs.getLong(columnIndex);
        if (rs.wasNull() || v <= 0L) return null;
        return toLocalDateTime(v);
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long v = cs.getLong(columnIndex);
        if (cs.wasNull() || v <= 0L) return null;
        return toLocalDateTime(v);
    }

    private LocalDateTime toLocalDateTime(long value) {
        if (value <= 0L) return null; // 关键：0 当作空
        return value < 1_000_000_000_000L
                ? LocalDateTime.ofInstant(Instant.ofEpochSecond(value), ZONE)
                : LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZONE);
    }
}